package com.water.wfo.component.util;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;

import java.util.Arrays;

/**
 * packageName com.water.wfo.component.util
 *
 * @author junhuili
 * @version JDK 8
 * @date 2024/5/28
 * @description TODO
 */
public class SM3Util {
    public static String encrypt(String src) {
        return ByteUtils.toHexString(hash(src.getBytes()));
    }

    /** * 计算SM3摘要值 * * @param srcData 原文 * @return 摘要值，对于SM3算法来说是32字节 */
    public static byte[] hash(byte[] srcData) {
        SM3Digest digest = new SM3Digest();
        digest.update(srcData, 0, srcData.length);
        byte[] hash = new byte[digest.getDigestSize()];
        digest.doFinal(hash, 0);
        return hash;
    }
    /** * 验证摘要 * * @param srcData 原文 * @param sm3Hash 摘要值 * @return 返回true标识验证成功，false标识验证失败 */
    public static boolean verify(byte[] srcData, byte[] sm3Hash) {
        byte[] newHash = hash(srcData);
        System.out.println(Hex.toHexString(newHash));
        System.out.println(Hex.toHexString(sm3Hash));
        if (Arrays.equals(newHash, sm3Hash)) {
            return true;
        } else {
            return false;
        }
    }
}
